
function defaultToStrFun (key: any): string {
  if (typeof key === null) {
    return 'null'
  } else if (typeof key === undefined) {
    return 'undefined'
  } else if (typeof key === 'string') {
    return `${key}`
  } else {
    return key.toString()
  }
}


class KeyValues {
  constructor (public key: string, public value: any) {}
  toString () {
    return `[${this.key}, ${this.value}]`
  }
}

// 字典类
class Dictionary {
  table: anyObj = {}

  constructor (public toStrFun = defaultToStrFun) {

  }

  // 是否存在key
  hasKey (key: any) {
    return this.table[ this.toStrFun(key) ] !== undefined
  }

  get length () {
    return Object.keys(this.table).length
  }
  // 设置
  set (key: any, value: any) {
    if (key !== null && value !== null) {
      const _key = this.toStrFun(key)
      this.table[ _key ] = new KeyValues(_key, value)
      return true
    }
    return false
  }
  // 获取值
  get (key: any) {
    const value = this.table[ this.toStrFun(key) ]
    return value ? value.value : undefined
  }
  // 删除
  remove (key: any) {
    if (this.hasKey(key)) {
      delete this.table[ this.toStrFun(key) ]
      return true
    }
    return false
  }
  // 是否为空
  isEmpty () {
    return this.length === 0
  }
  //清除所有
  clear () {
    if (this.length === 0) return true
    this.table = {}
    return true
  }
  // 返回键值对
  entires () {
    let arr = []
    if (!this.isEmpty()) {
      for (let key in this.table) {
        if (this.hasKey(key)) {
          arr.push(this.table[ this.toStrFun(key) ])
        }
      }
    }
    return arr
  }
  keys () {
    return Object.keys(this.table)
  }
  values () {
    return Object.values(this.table).map((item) => {
      return item.value
    })
  }
  // 遍历
  forEach (cb: (item: KeyValues, entires: Array<KeyValues>) => void) {
    if (!this.isEmpty()) {
      this.entires().forEach((couple: KeyValues, index, entires) => {
        cb(couple, entires)
      })
    }
  }
}

export default Dictionary
